package servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import entity.FitnessEquipment;
import service.FitnessEquipmentService;
import utils.Response;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "FitnessEquipmentServlet", value = "/FitnessEquipmentServlet")
public class FitnessEquipmentServlet extends HttpServlet {

    private FitnessEquipmentService fitnessEquipmentService = new FitnessEquipmentService();
    Response<Object> responseUtil = new Response<>();

    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String sortType = request.getParameter("sorttype");


        if (sortType.equals("list")) {
            // 调用Service类的方法查询所有健身器材信息
            List<FitnessEquipment> fitnessEquipmentList = fitnessEquipmentService.queryAllFitnessEquipments();
            // 将查询到的健身器材返回
            responseUtil.render(response, fitnessEquipmentList, 200);

        } else if (sortType.equals("delete")) {
            // 删除指定健身器材编号
            int sid = Integer.parseInt(request.getParameter("id"));
            fitnessEquipmentService.deleteFitnessEquipment(sid);
            responseUtil.render(response, true, 200);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        // 添加健身器材信息
        BufferedReader reader = request.getReader();
        FitnessEquipment fitnessEquipment = gson.fromJson(reader, FitnessEquipment.class);
        responseUtil.render(response, true, 200);
        fitnessEquipmentService.addFitnessEquipment(fitnessEquipment);
    }
}
